<?php

namespace Sharks\Core\Http\Routing;

use Sharks\Core\Support\Bag\Bag;
use Sharks\Core\Support\Bag\ParameterBag;
use Sharks\Core\Support\Storage\StorageArrayUtils;

/**
 * Route缓存
 * TODO: 目前使用手动写php文件作为缓存, 但性能及扩展性较差,可以改为FastCache使用
 */
class RouteCaching implements Bag {

    protected $hasChanged;
    protected $cache;

    public static function instance() {
        return new RouteCaching;
    }

    public function __construct() {
        $this->hasChanged = false;
        $routeCache = StorageArrayUtils::read('/route_cache.php');
        $this->cache = new ParameterBag($routeCache);
    }

    /**
     * 取值
     * @param $key
     * @param null $default
     * @return mixed
     */
    public function get($key, $default = null) {
        return unserialize($this->cache->get($key, $default));
    }

    /**
     * 取不到值就抛出异常
     * @param $key
     * @return array|null
     */
    public function getOrFail($key) {
        return $this->cache->getOrFail($key);
    }

    /**
     * 确认数据包中属性值是否存在
     * @param $key 属性名称
     * @return bool
     */
    public function has($key) {
        return $this->cache->has($key);
    }

    /**
     * 移除某名称的值
     * @param $key
     */
    public function forget($key) {
        $this->hasChanged = true;
        return unserialize($this->cache->forget($key));
    }

    /**
     * 设置某名称的值
     * @param $key
     * @param $value
     * @return mixed
     */
    public function put($key, $value) {
        $this->hasChanged = true;
        $this->cache->put($key, serialize($value));
    }

    /**
     * 原始数据,所有值
     * @return array
     */
    public function all() {
        return $this->cache->all();
    }

    public function store() {
        if ($this->hasChanged) {
            StorageArrayUtils::write('/route_cache.php', $this->cache->all());
        }
    }
}